<?php

class ContentPostsController extends ContentAppController{

	var $name = 'ContentPosts';
	protected $_allowActions = array();
	public function index(){
		Utils::loadModels($this, array('ContentPost'));
		$this->paginate = array(
			'conditions' => array(
				'ContentPost.type' => ContentPost::TYPE_POST,
				'ContentPost.status' => ContentPost::STATUS_PUBLIC,
			),
			'limit' => 10,
			'order' => 'ContentPost.id DESC',
		);
		$data = $this->paginate('ContentPost');
		$this->set(compact('data'));
	}

	function view($seo = null) {
		$hash = md5($seo, true);
		Utils::loadComponents($this, array('Content.ContentLogic'));
		$data = $this->ContentLogic->viewPost($hash);
		$this->set('title_for_layout', $data['ContentPost']['title']);
		$this->set(compact('data'));

		// get posts
		Utils::loadModels($this, array('ContentPost'));
		$posts = $this->ContentPost->find('all', array(
			'fields' => array(
				'ContentPost.seo_name', 'ContentPost.title'
			),
			'conditions' => array(
				'ContentPost.status' => ContentPost::STATUS_PUBLIC
			),
			'order' => 'id desc'
		));
		$this->set(compact('posts'));
	}

	public function system_index(){
		Utils::loadModels($this, array('ContentPost'));
		$this->paginate = array(
			'conditions' => array(
				'ContentPost.type' => ContentPost::TYPE_POST,
			),
			'limit' => 20,
			'order' => 'ContentPost.id DESC',
		);
		$data = $this->paginate('ContentPost');
		$this->set(compact('data'));
	}

	public function widget_latest_posts(){
		Utils::loadModels($this, array('ContentPost'));
		$posts = $this->ContentPost->find('all', array(
			'fields' => array(
				'ContentPost.seo_name', 'ContentPost.title'
			),
			'conditions' => array(
				'ContentPost.status' => ContentPost::STATUS_PUBLIC
			),
			'order' => 'id desc'
		));
		$this->set(compact('posts'));
		return $this->render('/content_posts/widget_latest_posts');
	}

	public function system_edit($id = null){
		Utils::loadComponents($this, array('Content.ContentLogic'));
		if($this->isPost()){
			$this->data['ContentAuthor']['email'] = $this->Auth->user('email');
			$this->data['ContentPost']['seo_md5_raw'] = md5($this->data['ContentPost']['seo_name'], true);
			$this->data['ContentPost']['id'] = $id;
			$result = $this->ContentLogic->savePost($this->data);
			if(!$result['status']){
				$this->Session->setFlash('Tạo bài viết thành công');
				$this->redirect('/system/content/content_posts');
			} else {
				$this->Session->setFLash($result['message']);
			}
		} else {
			$this->data = $this->ContentPost->findById($id);
		}
	}
}